package viewer;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Robot;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;

/**
 *
 * @author Ivan
 */
public class MyColorPanel extends JPanel {
    public Image palImg = null;
    public Robot robot = null;
    private ColorChoseable obj;
    public Color color = Color.BLACK;
    public int x, y;
    public MyColorPanel(ColorChoseable obj) {
        setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        this.obj = obj;
        try {
            robot = new Robot();
        }
        catch (Exception e)  {
            e.printStackTrace();
        }


        addMouseMotionListener(new MouseMotionListener() {
            public void mouseDragged(MouseEvent e) {
                setColor(e);
            }

            public void mouseMoved(MouseEvent e) {
            }
        });

        addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent e) {

            }

            public void mousePressed(MouseEvent e) {
                setColor(e);
            }

            public void mouseReleased(MouseEvent e) {
            }

            public void mouseEntered(MouseEvent e) {
            }

            public void mouseExited(MouseEvent e) {
            }


        });
        
        palImg = java.awt.Toolkit.getDefaultToolkit().getImage(getClass().getResource("palette.png"));
        setSize(181, 101);
    }
    
    private void setColor(MouseEvent e) {
        x = e.getXOnScreen();
        y = e.getYOnScreen();
        if ((e.getX()<0)||(e.getX()>getWidth()))
                return;
        if ((e.getY()<0)||(e.getY()>getHeight()))
                return;

        if (robot!=null)
            color = robot.getPixelColor(x, y);
        if (obj!=null)
            obj.onChangeColor(color);
    }

    @Override
    public void paintComponent(Graphics g) {
        if (palImg!=null)
            g.drawImage(palImg, 0, 0, this);
    }

}
